<template>
  <div class="WorkflowType">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>门户管理</el-breadcrumb-item>
      <el-breadcrumb-item><a>应用分类</a></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="search-content">
      <el-input
        placeholder="请输入分类名称"
        prefix-icon="el-icon-search"
        v-model="searchInput"
        @input="searching"
      ></el-input>
      <div class="search-res">
        <div class="no-res" v-if="searchInput && !searchRes.length">未找到</div>
        <div v-else-if="searchInput" class="search-select">
          <i class="el-icon-arrow-left" @click="leftClick"></i>
          <span>{{ currentRes }} / {{ searchRes.length }}</span>
          <i class="el-icon-arrow-right" @click="rightClick"></i>
        </div>
      </div>
    </div>
    <div class="tableShow">
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handleradd"
        :disabled="loading"
        id="add"
        >添加</el-button
      >
      <div class="table-content scroll-content">
        <table>
          <thead>
            <tr>
              <th scope="col">序号</th>
              <th scope="col" style="width: 350px">分类名称</th>
              <th scope="col">是否显示</th>
              <th scope="col">添加日期</th>
              <th scope="col">操作</th>
            </tr>
          </thead>
          <draggable
            v-model="typeInfo"
            tag="tbody"
            @change="Sortchange"
            v-bind="getOptions()"
          >
            <tr
              v-for="(item, index) in typeInfo"
              :key="item.category_id"
              :id="`type${item.category_id}`"
              :class="item.isactive ? 'active' : ''"
            >
              <td>{{ index + 1 }}</td>
              <td
                class="reletive"
                :class="item.isinput ? 'isinput' : ''"
                @click="handlerDbclick(item)"
              >
                <el-tooltip
                  effect="dark"
                  :content="item.category_name.zh"
                  placement="top"
                  v-if="!item.isinput && item.category_name.zh.length >= 20"
                  popper-class="resettooltip"
                >
                  <div>
                    {{ slicename(item.category_name.zh) }}
                  </div>
                </el-tooltip>
                <div
                  class="edit"
                  v-if="!item.isinput && item.category_name.zh.length < 20"
                >
                  {{ item.category_name.zh }}
                </div>
                <el-input
                  v-model="item.category_name.zh"
                  :id="`input` + item.category_id"
                  v-if="item.isinput"
                  class="resetinput"
                ></el-input>
                <el-popover
                  placement="bottom-end"
                  popper-class="resetpopper"
                  v-if="item.isinput"
                >
                  <el-form label-width="60px">
                    <el-form-item label="中文：">
                      <el-input
                        v-model="item.category_name.zh"
                        placeholder="请输入"
                        clearable
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="英文：">
                      <el-input
                        v-model="item.category_name.en"
                        placeholder="please input"
                        clearable
                      ></el-input>
                    </el-form-item>
                  </el-form>
                  <i slot="reference" class="iconfont icon-guojihua"></i>
                </el-popover>
              </td>
              <td>
                <el-switch
                  v-model="item.show"
                  @change="statusChange(item)"
                ></el-switch>
              </td>
              <td>{{ item.add_time }}</td>
              <td>
                <span
                  @click="deleteClick(item)"
                  class="el-icon-delete"
                  style="margin-right: 12px; cursor: pointer"
                ></span>
              </td>
            </tr>
          </draggable>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import uuidv1 from "uuid/v1";
import tools from "@/utils/tools";
import {
  addCategory,
  changeOrder,
  changeStatus,
  deleteCategory,
  getAllCategory,
  updateCategory,
} from "@/http/api";
import dayjs from "dayjs";
export default {
  name: "WorkflowType",
  components: { draggable },
  data() {
    return {
      searchRes: [],
      searchInput: "",
      typeInfo: [],
      currentRes: -1,
      beforeDom: null,
      edititem: null, // 正在编辑的item
      newadd: "", // 当前新增id
      loading: false,
    };
  },
  mounted() {
    this.reload();
  },
  methods: {
    searching() {
      if (this.searchInput) {
        this.searchRes = this.typeInfo.filter((type) => {
          return type.category_name.zh.includes(this.searchInput);
        });
        if (this.searchRes.length) {
          this.currentRes = 1;
          this.changeCurrent();
        } else {
          this.beforeDom
            ? (this.beforeDom.style.backgroundColor = "#fff")
            : null;
        }
      } else {
        this.beforeDom ? (this.beforeDom.style.backgroundColor = "#fff") : null;
        this.searchRes.length = 0;
        this.currentRes = -1;
      }
    },
    leftClick() {
      this.currentRes > 1
        ? (this.currentRes -= 1)
        : (this.currentRes = this.searchRes.length);
      this.changeCurrent();
    },
    rightClick() {
      this.currentRes < this.searchRes.length
        ? (this.currentRes += 1)
        : (this.currentRes = 1);
      this.changeCurrent();
    },
    changeCurrent() {
      let element = document.querySelector(
        "#type" + this.searchRes[this.currentRes - 1].category_id
      );
      this.beforeDom ? (this.beforeDom.style.backgroundColor = "#fff") : null;
      this.beforeDom = element;
      element.style.backgroundColor = "#FFF6E5";
      element.scrollIntoViewIfNeeded(true);
    },
    tableRowClassName({ row }) {
      return row.id;
    },
    async deleteClick(item) {
      this.$confirm(
        "删除此分类后，该分类下数据将归属于其他分类，是否确定删除？",
        "提醒",
        {
          confirmButtonText: "确定",
          closeOnClickModal: false,
          closeOnPressEscape: false,
          customClass: "message-box-tit1",
          callback: async (action) => {
            if (action === "confirm") {
              let res = {};
              if (item.tenant_id !== undefined) {
                res = await deleteCategory(item.category_id);
              }
              if (res.code === 20021 || JSON.stringify(res) === "{}") {
                this.$message.success("删除成功");
                this.reload();
                this.searching();
              } else {
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              }
            } else {
              document
                .getElementById("input" + this.edititem.category_id)
                ?.focus();
            }
          },
        }
      );
    },
    async reload() {
      let res = await getAllCategory();
      if (res.code === 20041) {
        this.typeInfo = res.data.filter(
          (item) => item.category_name_en !== "other"
        );
        this.typeInfo.forEach((element) => {
          element.show = element.show ? true : false;
          element.add_time = dayjs(element.add_time).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        });
      }
      for (let index = 0; index < this.typeInfo.length; index++) {
        const element = this.typeInfo[index];
        this.$set(element, "isinput", false);
        this.$set(element, "isactive", false);
      }
      this.newadd = "";
    },
    getOptions() {
      return {
        forceFallback: false,
        animation: 150,
      };
    },
    // 排序改变
    async Sortchange({ moved }) {
      let res = await changeOrder({
        oldIndex: moved.oldIndex,
        newIndex: moved.newIndex,
      });
      if (res.code === 20030) {
        this.$message({
          type: "error",
          message: "更改失败",
        });
      } else {
        this.$message.success("更新成功");
      }
    },
    // 点击变input框
    handlerDbclick(item) {
      this.edititem = JSON.parse(JSON.stringify(item));
      this.typeInfo.map((item) => {
        this.$set(item, "isinput", false);
      });
      this.$set(item, "isinput", true);
      document.addEventListener("click", this.documentClickHandler);
    },
    // 监听全局点击事件,点击空白处取消激活状态
    async documentClickHandler(e) {
      if (
        (e.target.closest(".reletive") && e.target.closest(".isinput")) ||
        e.target.closest("#add") ||
        e.target.closest(".edit") ||
        e.target.closest(".el-icon-delete") ||
        e.target.closest(".el-button")
      ) {
        return;
      } else {
        let _index = this.typeInfo
          .map((item) => {
            return item.category_id === this.edititem.category_id;
          })
          .indexOf(true);
        if (
          this.typeInfo[_index].category_name &&
          this.typeInfo[_index].category_name.zh.trim() === ""
        ) {
          this.$confirm("分类名称不可为空", "提醒", {
            confirmButtonText: "确定",
            closeOnClickModal: false,
            closeOnPressEscape: false,
            customClass: "message-box-tit1",
            showCancelButton: false,
            showClose: true,
            callback: (action) => {
              if (action === "confirm" || action === "cancel") {
                this.$set(
                  this.typeInfo[_index],
                  "category_name",
                  this.edititem.category_name
                );
                document
                  .getElementById("input" + this.edititem.category_id)
                  ?.focus();
                document.addEventListener("click", this.documentClickHandler);
              }
            },
          });
        }
        let currentSelect = this.typeInfo[_index].category_name;
        let beforeInfo = this.edititem.category_name;
        if (
          JSON.stringify(currentSelect) != JSON.stringify(beforeInfo) &&
          currentSelect.zh !== ""
        ) {
          let processCategorySaveParam = { ...this.typeInfo[_index] };
          processCategorySaveParam.show = processCategorySaveParam.show ? 1 : 0;
          processCategorySaveParam.add_time = dayjs(
            processCategorySaveParam.add_time
          ).valueOf();
          processCategorySaveParam.category_name_zh =
            processCategorySaveParam.category_name.zh;
          processCategorySaveParam.category_name_en =
            processCategorySaveParam.category_name.en;
          let res = {};
          if (processCategorySaveParam.category_id !== undefined) {
            res = await updateCategory(processCategorySaveParam);
          } else {
            processCategorySaveParam.order = _index;
            res = await addCategory(processCategorySaveParam);
          }
          // *** 发请求添加或编辑成功 ***
          res = { code: "000000" };
          if (res.code === "000000") {
            if (this.typeInfo[_index].id === this.newadd) {
              this.$message.success("添加成功");
            } else {
              this.$message.success("编辑成功");
            }
            this.reload();
          } else {
            if (res.message) {
              document
                .getElementById("input" + this.edititem.category_id)
                ?.focus();
              this.$message.error(res.message);
            }
          }
        } else {
          if (this.typeInfo[_index].category_name.zh !== "") {
            this.typeInfo.map((item) => {
              this.$set(item, "isinput", false);
            });
          }
        }
        document.removeEventListener("click", this.documentClickHandler);
      }
    },
    handleradd() {
      this.loading = true;
      this.typeInfo.map((item) => {
        this.$set(item, "isinput", false);
      });
      let currentTime = uuidv1();
      this.newadd = currentTime;
      let _item = {
        category_name: {
          en: "",
          zh: "",
        },
        add_time: tools.formatDate(new Date()),
        id: currentTime,
        isactive: false,
        isinput: true,
        show: false,
      };
      // 新增分类获得焦点
      this.edititem = JSON.parse(JSON.stringify(_item));
      this.typeInfo.push(_item);
      setTimeout(() => {
        document.getElementById("input" + this.edititem.category_id)?.focus();
      });
      // 点击其他地方失焦
      document.addEventListener("click", this.documentClickHandler);
      this.loading = false;
    },
    slicename(name) {
      if (name.length > 20) {
        return name.slice(0, 20) + "...";
      } else {
        return name;
      }
    },
    async statusChange(item) {
      let params = { ...item };
      params.show = params.show ? 1 : 0;
      params.add_time = dayjs(params.add_time).valueOf();
      let res = await updateCategory(params);
      if (res.code === 20031) {
        this.$message.success("执行成功");
      } else {
        if (res.message) {
          this.$message.error(res.message);
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.WorkflowType {
  .search-content {
    width: 100%;
    padding: 20px;
    margin-bottom: 20px;
    background-color: #fff;
    position: relative;
    .search-res {
      position: absolute;
      right: 35px;
      top: 50%;
      transform: translateY(-50%);
      .no-res {
        color: #ccc;
      }
      .search-select {
        i {
          cursor: pointer;
        }
        span {
          padding: 0 12px;
        }
      }
    }
  }
  .tableShow {
    padding: 20px;
    background: #fff;
    height: calc(100vh - 250px);
    width: 100%;
    .table-content {
      margin-top: 20px;
      height: calc(100vh - 340px);
      &::before {
        display: none;
      }
      &.active-bar::-webkit-scrollbar-thumb {
        display: block;
      }
      table {
        border-collapse: collapse;
        width: 100%;
      }
      thead tr th {
        background-color: #fafafa;
        height: 50px;
        color: #909399;
      }
      .el-icon-delete {
        cursor: pointer;
      }
      tr.active {
        background-color: #fff6e5;
      }
    }
    .icon-guojihua {
      position: absolute;
      top: 32%;
      right: 5px;
      &:hover {
        color: #3c8cff;
      }
      cursor: pointer;
    }
    td {
      font-size: 14px;
      border-bottom: 1px solid #e8e8e8;
      text-align: center;
      height: 50px;
    }
    tr:hover {
      background-color: #f7f8fc !important;
    }
  }
}
</style>
